package com.stanwind.wmqtt.auth.def;

import com.stanwind.wmqtt.auth.AuthSettingFactory;
import com.stanwind.wmqtt.auth.domain.MQTTBasicAuthInfo;
import com.stanwind.wmqtt.auth.domain.MQTTClientConnData;
import com.stanwind.wmqtt.auth.domain.MQTTServerConnData;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static org.eclipse.paho.client.mqttv3.MqttConnectOptions.MQTT_VERSION_3_1_1;

/**
 * DefaultSettingFactory 默认不处理
 *
 * @author : Stan
 * @version : 1.0
 * @date :  2020-11-11 15:44
 **/
public class DefaultSettingFactory implements AuthSettingFactory {
    private static final Logger log = LoggerFactory.getLogger(DefaultSettingFactory.class);

    @Autowired
    private MQTTBasicAuthInfo authBean;

    @Override
    public MQTTClientConnData getClientConnData(List<String> readTopics, List<String> writeTopics) throws Exception {
        Long expire = System.currentTimeMillis() + TOKEN_EXPIRE;
        //直接返回账号密码
        return new MQTTClientConnData().setUsername(authBean.getUsername()).setPassword(authBean.getPassword()).setExpire(expire);
    }

    @Override
    public MQTTServerConnData getServerConnData(String[] serverURIs, Integer keepAliveInterval, MQTTBasicAuthInfo authBean) {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(serverURIs);
        options.setUserName(authBean.getUsername());
        options.setPassword(authBean.getPassword().toCharArray());
        options.setKeepAliveInterval(keepAliveInterval);
        options.setCleanSession(false);
        options.setKeepAliveInterval(keepAliveInterval);
        options.setAutomaticReconnect(true);
        options.setMqttVersion(MQTT_VERSION_3_1_1);
        options.setConnectionTimeout(5000);


        return new MQTTServerConnData().setConnectOptions(options);
    }
}
